'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 开服限购
 * @author agl
 */

var _ = require('lodash');
var async = require('async');
var moment = require('moment');
var Code = require('../../../consts/code');
var moduleType = require('../../../consts/moduleType');
var operationType = require('../../../consts/operationType');
var configUtil = require('../../../util/configUtil');
var constantUtil = require('../../../util/constantUtil');
var PlayerManager = require('../../../libs/playerManager');
var rewardService = require('../../../services/rewardService');
var roleService = require('../../../services/roleService');
var dataApi = require('../../../libs/dataApi.js');
var chatType = require('../../../consts/chatType.js');
var sysMsgType = require('../../../consts/sysMsgType.js');
var sysMsgConf = require('../../../config/sysMsgConf.js');
var soldierConf = require('../../../config/soldierConf.js');
var chatMgr = require('../../../mgr/chatMgr.js');

module.exports = function (app) {
    return new Handler(app);
};

var Handler = function (app) {
    this.app = app;
};

/**
 * 开服限购
 */
Handler.prototype.buy = function (msg, session, next) {
    var role_id = session.uid;
    var role_model;
    // jshint maxstatements:100
    var player_manager = new PlayerManager(role_id);
    var reward_list = [];
    async.waterfall(
        [

            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(
                    ['role', 'activity', 'bag', 'build', 'soldier', 'accrued', 'soldier'],
                    cb
                );
            },
            function (cb) {
                var activity_model = player_manager.activity;
                var role_model = player_manager.role;
                var open_game_time = configUtil.getOpenGameTime();
                var now_tm = moment().unix();
                var day_num = Math.ceil((now_tm - open_game_time + 1) / configUtil.second_per_day);
                var activity_days = constantUtil.value('open_service_time');

                // 活动是否已过期
                if (day_num > activity_days) {
                    return next(null, {
                        code: Code.ACTIVITY_OUT_OF_DATE
                    });
                }

                // 扣减可购买次数
                var remain_times = activity_model.limit_buy_remain_times;
                if (!activity_model.decLimitBuyTimes()) {
                    return next(null, {
                        code: Code.ACTIVITY_LIMIT_BUY_NO_TIMES
                    });
                }

                // 次数编号
                var limit_buy_times_per_day = constantUtil.value('limit_buy_times_per_day');
                var time_num = day_num * limit_buy_times_per_day - remain_times + 1;
                // var time_num = 10;
                // 扣除钻石
                var cost_conf = dataApi.open_limit_cost.findById(time_num);
                if (!cost_conf) {
                    return next(null, {
                        code: Code.ACTIVITY_OUT_OF_DATE
                    });
                }
                var open_limit_buy_price = cost_conf.point_cost;
                if (!roleService.subDiamond(player_manager, moduleType.MDL_ACT_OPEN_LIMIT_BUY, operationType.OPR_OPEN_LIMIT_BUY, open_limit_buy_price)) {
                    return next(null, {
                        code: Code.USER_DIAMOND_NOT_ENOUGH
                    });
                }

                // 取出配置
                var soldier_name = '';
                var reward_conf = dataApi.open_limit_buy.findById(time_num);
                if (!reward_conf) {
                    return next(null, {
                        code: Code.ACTIVITY_OUT_OF_DATE
                    });
                }

                // 三个中随机抽取一个
                var random_reward_item = _getRandReward(reward_conf);
                reward_list.push(random_reward_item);
                if (random_reward_item.reward_type === 25) {
                    var soldier_item = soldierConf.getSoldierTypeConf(random_reward_item.reward);

                    if (!!soldier_item) {
                        soldier_name = soldier_item.name;
                    }

                    // 发放广播
                    var time_buy = sysMsgConf.getMsgConf(sysMsgType.TIMEBUY);
                    _.some(time_buy, function (time_buy_item) {
                        if (soldier_item.quality === time_buy_item.value) {
                            var role_name = role_model.name;
                            var time_buy_content = time_buy_item.format;
                            var time_buy_content_msg1 = time_buy_content.replace(/name/, role_name);
                            var time_buy_content_msg = time_buy_content_msg1.replace(/soldier/, soldier_name);

                            var name = '系统';
                            var time_buy_param = {
                                type: chatType.SYSTEM,
                                name: name,
                                msg: time_buy_content_msg,
                                time: moment().unix()
                            };
                            _chatMsg(time_buy_param);
                            return true;
                        }
                    });
                }
                rewardService.addRewardListToRole(player_manager, reward_list, moduleType.MDL_ACT_OPEN_LIMIT_BUY, operationType.OPR_ACT_OPEN_LIMIT_BUY);
                player_manager.save(cb);
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }
            return next(null, {
                code: Code.OK,
                result: {
                    reward_list: reward_list
                }
            });
        }
    );
};

var _getRandReward = function (reward_conf) {
    var probability_list = [];
    var total = 0;
    var index = 0;
    _.forEach(reward_conf, function (item) {
        total += item.probability;
        probability_list.push({
            index: index,
            probability: total
        });
        index++;
    });

    var rand_val = _.random(0, total - 1);
    var reward_info = null;
    _.forEach(probability_list, function (prob_item) {
        if (rand_val < prob_item.probability) {
            reward_info = reward_conf[prob_item.index];
            return false;
        }
        return true;
    });

    return {
        reward: reward_info.reward,
        reward_type: reward_info.reward_type,
        reward_num: reward_info.reward_num,
        reward_value: reward_info.reward_value,
        probability: reward_info.probability
    };
};

var _chatMsg = function (param) {
    chatMgr.sendWorld(param, function (err, fails) {
        if (err) {
            console.error('send message to world error: %j, fail ids: %j', err, fails);
            return;
        }
    });
};
